import React, {useState} from "react"
import {Button, message, PageHeader, Table, Upload, Tag, Divider, Popconfirm, Modal, Form, Select, Input, Radio, Popover} from "antd";
import {ArrowLeftOutlined, PlusOutlined, ExclamationCircleOutlined, LoadingOutlined, UploadOutlined, QuestionCircleOutlined, VerticalAlignBottomOutlined} from "@ant-design/icons";
import cs from "classnames";
import SearchAutoComplete from "libs/search-auto-complete"
import {useRequest} from '@umijs/hooks'
import {pageSetting, HOST, orderType} from "project-config"
import {useTableCheck, formatResult} from "../../shared/libs/hooks/table-hooks"
import {get} from "server"
import {del, putJSON} from "../../shared/server"

import {clearner} from "../../shared/libs/utils"
import highlight from "../../shared/libs/highlight";
import {downloadSync} from "../../shared/libs/download"
import "./index.less"

const {confirm} = Modal;

const {Option} = Select;

const amountRender = v => <span><span>￥</span>{v}</span>

const Product = (props) => {

	const [form] = Form.useForm();

	const onDelete = (id) => {
		del(`/management/product/${id}`).then((data) => {
			if (data) {
				message.success('产品删除成功')
				onSearch()
			}
		})
	}

	const enableProduct = (row) => {
		putJSON(`/management/product/toggle/${row.id}?activated=${!row.activated}`).then((data) => {
			if (data) {
				message.success(data.activated ? "上架成功" : "下架成功")
				onSearch()
			}
		})
	}

	const updateProduct = (id) => {
		props.history.push(`/app/product/edit/${id}`)
	}

	//获取数据
	const getPageData = ({
		                     current, pageSize, sorter, filters, searchKey,
		                     // priceKey, priceFrom, priceTo
	                     }) => {
		let activated;
		if (filters && filters.activated && filters.activated.length === 1) {
			activated = filters.activated[0];
		}
		let sortKey;
		let sortType;
		if (sorter && sorter.columnKey && sorter.order) {
			sortKey = sorter.columnKey;
			sortType = orderType[sorter.order];
		}
		return get(`/management/product/${pageSize}/${current}`, clearner({
			searchKey,
			sortType,
			sortKey,
			activated,
			// priceKey,
			// priceFrom,
			// priceTo,
		}))
	}


	//表格选中
	const {rowSelection, items} = useTableCheck({})
	//
	const {tableProps, params, refresh, pagination} = useRequest(getPageData, {
			paginated: true,
			defaultPageSize: 10,
			formatResult,
		}
	)

	const onSearch = (searchKey) => {
		params[0].searchKey = searchKey
		refresh().finally()
	}

	const onDeleteBatch = () => {
		if (items != null) {
			del(`/management/product/batch/${items.join(',')}`).then(result => {
				if (result) {
					message.success(`成功删除 ${items.length} 条用户`)
					onSearch()
				}
			})
		}
	}

	const onEnabledBatch = () => {
		if (items != null) {
			putJSON(`/management/product/batch/toggle/${items.join(',')}`, {activated: true}).then(result => {
				if (result) {
					message.success(`成功上架 ${items.length} 条产品`)
					onSearch()
				}
			})
		}
	}

	const onDisabledBatch = () => {
		if (items != null) {
			putJSON(`/management/product/batch/toggle/${items.join(',')}`, {activated: false}).then(result => {
				if (result) {
					message.success(`成功下架 ${items.length} 条产品`)
					onSearch()
				}
			})
		}
	}

	const showConfirm = (handle) => {
		const batchMapping = {
			Delete: {
				key: "删除",
				func: onDeleteBatch
			},
			Enabled: {
				key: "上架",
				func: onEnabledBatch
			},
			Disabled: {
				key: "下架",
				func: onDisabledBatch
			},
		}
		confirm({
			title: `确认${batchMapping[handle].key}`,
			icon: <ExclamationCircleOutlined/>,
			content: `确认要${batchMapping[handle].key}以下${items.length}记录?`,
			onOk() {
				batchMapping[handle].func();
			},
			onCancel() {
			},
		});
	}

	const productColumns = [
		{
			title: "项目编号",
			dataIndex: "itemNo",
			key: "itemNo",
			render: (v) => highlight(v, params[0].searchKey)
		}, {
			title: '项目名',
			key: 'name',
			dataIndex: 'name',
			render: (v, record) => {
				const content = <div>
					<p>说明：{record.description}</p>
					<p>备注：{record.remarks}</p>
				</div>
				return <div style={{display: "flex", alignItems: "center"}}>
					{highlight(v, params[0].searchKey)}
					<Popover content={content} title="">
						<QuestionCircleOutlined style={{color: "#1890ff", marginLeft: 5}}/>
					</Popover>
				</div>
			}
		}, {
			title: '简码',
			width: 100,
			key: 'briefCode',
			dataIndex: 'briefCode',
			render: (v) => highlight(v, params[0].searchKey)
		},{
			title: '分类',
			width: 100,
			key: 'category',
			dataIndex: 'category'
		}, {
			title: '固定成本价',
			key: 'fixedCostPrice',
			dataIndex: 'fixedCostPrice',
			sorter: true,
			showSorterTooltip: false,
			sortDirections: ['ascend', 'descend', 'ascend'],
			render: amountRender
		}, {
			title: '可变成本价',
			key: 'volatileCostPrice',
			dataIndex: 'volatileCostPrice',
			sorter: true,
			showSorterTooltip: false,
			sortDirections: ['ascend', 'descend', 'ascend'],
			render: amountRender
		}, {
			title: '其他成本价',
			key: 'otherCostPrice',
			dataIndex: 'otherCostPrice',
			sorter: true,
			showSorterTooltip: false,
			sortDirections: ['ascend', 'descend', 'ascend'],
			render: amountRender
		}, {
			title: '市场价',
			key: 'marketPrice',
			dataIndex: 'marketPrice',
			sorter: true,
			showSorterTooltip: false,
			sortDirections: ['ascend', 'descend', 'ascend'],
			render: amountRender
		}, {
			title: '状态',
			key: 'activated',
			dataIndex: 'activated',
			filters: [
				{text: "上架中", value: true},
				{text: "已下架", value: false}
			],
			render: (text) => text ? <Tag color="#4CAF50" className="large">上架中</Tag> : <Tag className="large" color="#f50">已下架</Tag>
		}, {
			title: '操作',
			key: 'action',
			render: (_, record) => (
				<>
					<a onClick={() => updateProduct(record.id)}>编辑</a>
					<Divider type="vertical"/>
					<Popconfirm
						title={`确定要${record.activated ? "下架" : "上架"}此产品吗?`}
						placement="rightBottom"
						onConfirm={() => enableProduct(record)}
					>
						<a>{record.activated ? "下架" : "上架"}</a>
					</Popconfirm>
					<Divider type="vertical"/>
					<Popconfirm
						title="确定要删除此产品吗?"
						placement="rightBottom"
						onConfirm={() => onDelete(record.id)}
					>
						<a>删除</a>
					</Popconfirm>
				</>
			)
		}
	]

	// const onFinish = values => {
	// 	const {price: {priceKey, priceFrom, priceTo}, searchKey} = values;
	// 	params[0] = {
	// 		...params[0],
	// 		priceKey,
	// 		priceFrom,
	// 		priceTo,
	// 		searchKey
	// 	}
	// 	refresh().finally()
	// }

	// const resetSearch = () => {
	// 	setHasPriceField(false);
	// 	form.resetFields();
	// 	params[0] = {
	// 		...params[0],
	// 		priceKey: "",
	// 		priceFrom: "",
	// 		priceTo: "",
	// 		searchKey: ""
	// 	}
	// 	refresh().finally()
	// }

	// const [hasPriceFiled, setHasPriceField] = useState(false)

	// const handlePriceField = (value) => {
	// 	if (value) setHasPriceField(true);
	// }

	const [loading, setLoading] = useState(false);

	const onFileChange = ({file}) => {
		const {response} = file;
		console.log(response, "response")
		setLoading(true);
		if (!response) {
			setLoading(true);
			return;
		}
		if (response.data.failedList && response.data.failedList[0] && response.data.failedList[0].message) {
			message.error(response.data.failedList[0].message)
			setLoading(false)
			return;
		}
		message.success("导入成功")
		setLoading(false);
		refresh().finally()
	}

	// const [importStyle, setImportStyle] = useState("append");

	const btnPrpos = {
		type: 'primary',
		disabled: items.length < 1,
		ghost: true,
		style: {marginLeft: 10}
	}

	return (
		<div className={'zr-panel'}>
			<div className={'zr-panel-header'}>
				<PageHeader backIcon={<ArrowLeftOutlined/>} onBack={() => window.history.back()} title='项目管理' subTitle=''/>
			</div>
			<div className={'zr-list-page-box body-bg body-border absolute'}>
				{/* <Form
					form={form}
					name="basic"
					onFinish={onFinish}
					layout="inline"
					style={{
						margin: "20px 20px 0 20px",
						justifyContent: "flex-end",
					}}
				>
					<Form.Item name="searchKey" label={"查询关键字"}>
						<Input placeholder="请输入产品名或拼音码"/>
					</Form.Item>
					<Form.Item label={'价格区间'}>
						<Input.Group compact>
							<Form.Item
								name={['price', 'priceKey']}
								noStyle
							>
								<Select placeholder="选择价格属性" onChange={handlePriceField}>
									<Option key="fixedCostPrice" value="fixedCostPrice">成本价</Option>
									<Option key="marketPrice" value="marketPrice">市场价</Option>
									<Option key="volatileCostPrice" value="volatileCostPrice">可变成本价</Option>
									<Option key="otherCostPrice" value="otherCostPrice">其他成本价</Option>
								</Select>
							</Form.Item>
							<Form.Item name={['price', 'priceFrom']}>
								<Input style={{width: 100, textAlign: 'center'}} placeholder="最小值" disabled={!hasPriceFiled}/>
							</Form.Item>
							<Input
								style={{
									width: 40,
									borderLeft: 0,
									borderRight: 0,
									pointerEvents: 'none',
								}}
								placeholder="到"
								// disabled
							/>
							<Form.Item name={['price', 'priceTo']}>
								<Input
									style={{
										width: 100,
										textAlign: 'center',
									}}
									placeholder="最大值"
									disabled={!hasPriceFiled}
								/>
							</Form.Item>
						</Input.Group>
					</Form.Item>
					<Form.Item>
						<Button type="primary" htmlType="submit" style={{marginRight: 10}}>
							<SearchOutlined/> 查询
						</Button>
						<Button onClick={resetSearch}><CloseOutlined/> 重置</Button>
					</Form.Item>
				</Form> */}
				<div className={cs("zr-query-box")} style={{paddingRight: 20,}}>
					<SearchAutoComplete style={{marginRight: 5}} allowClear={true} onSelect={onSearch} placeholder="请输入关键字查询"/>
					<Button style={{margin: "0 10px"}} type="primary" onClick={() => props.history.push("/app/product/add")}><PlusOutlined/>添加项目</Button>
					{/* <Radio.Group value={importStyle} onChange={(event) => {
							setImportStyle(event.target.value)
						}}>
							<Radio.Button value="append" key="1">普通</Radio.Button>
							<Radio.Button value="overwrite" key="2">智能合并</Radio.Button>
							<Radio.Button value="replaceAll" key="3">完全覆盖</Radio.Button>
						</Radio.Group> */}
					<Upload
						accept=".xls,.xlsx"
						name="file"
						action={`${HOST}/management/product/import/overwrite`}
						multiple={false}
						withCredentials={true}
						showUploadList={false}
						onChange={onFileChange}
					>
						<Button type={'primary'}>{loading ? <LoadingOutlined/> : <UploadOutlined/>} 从文件导入 </Button>
					</Upload>
					<Button type={'primary'}
					        onClick={() => downloadSync(`${HOST}/management/product/export`, "项目.xls")}
					        style={{marginLeft: 10}}>
						<VerticalAlignBottomOutlined/> 导出项目
					</Button>
					<Button
						{...btnPrpos}
						onClick={() => showConfirm("Enabled")}
					>
						批量上架
					</Button>
					<Button
						{...btnPrpos}
						onClick={() => showConfirm("Disabled")}
					>
						批量下架
					</Button>
					<Button
						{...btnPrpos}
						ghost={false}
						danger
						onClick={() => showConfirm("Delete")}
					>
						批量删除
					</Button>

				</div>
				<div className="zr-table-box">
					<Table
						{...tableProps}
						pagination={{
							...pagination,
							...pageSetting
						}}
						rowSelection={rowSelection}
						rowKey={record => record.id}
						size='middle'
						columns={productColumns}/>
				</div>
			</div>
		</div>
	)
}

export default Product;